package com.yjh.admin.controller.user;


import annotation.Inner;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjh.admin.config.data.DataSource;
import com.yjh.admin.dto.user.UserRoleDto;
import com.yjh.admin.entity.user.SysUserRole;
import com.yjh.admin.server.sys.SysUserRoleService;
import com.yjh.admin.server.sys.SysUserService;
import com.yjh.admin.util.SecurityUtils;
import enums.SysUser;
import enums.UserInfo;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import util.R;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 用户表
 *
 * @author smithGuo
 * @date 2020-07-01 08:38:57
 */
@ApiOperation("用户")
@RestController
@AllArgsConstructor
@RequestMapping("/user")
public class UserController {

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
    private final SysUserService sysUserService;

    private final SysUserRoleService sysUserRoleService;



    /**
     * 获取当前用户全部信息
     *
     * @return 用户信息
     */
    @GetMapping(value = {"/info"})
    @DataSource("sys_db")
    public R info() {
        String username = SecurityUtils.getUser().getUsername();
        SysUser user = sysUserService.getOne(Wrappers.<SysUser>query()
                .lambda().eq(SysUser::getUsername, username));
        if (user == null) {
            return new R<>(Boolean.FALSE, "获取当前用户信息失败");
        }
        return new R<>(sysUserService.findUserInfo(user));
    }

    /**
     * 获取指定用户全部信息
     *
     * @return 用户信息
     */
    @Inner
    @GetMapping("/info/{username}")
    @DataSource("sys_db")
    public R info(@PathVariable String username) {
        SysUser user = sysUserService.getOne(Wrappers.<SysUser>query()
                .lambda().eq(SysUser::getUsername, username));
        if (user == null) {
            return new R<>(Boolean.FALSE, String.format("用户信息为空 %s", username));
        }
        return new R<>(sysUserService.findUserInfo(user));
    }



    /**
     * 分页查询
     * @param page 分页对象
     * @param sysUser 用户表
     * @return
     */
    @ApiOperation("分页查询")
    @PostMapping("/page")
    @DataSource("sys_db")
    public R getSysUserPage(@RequestBody Page page, SysUser sysUser) {
        List<UserRoleDto>  userRoleDtoList = new ArrayList<>();
        IPage<SysUser> pages = sysUserService.page(page, Wrappers.query(sysUser));

        List  userId = new ArrayList();
        for(SysUser user:pages.getRecords()){
            userId.add(user.getUserId());
        }
        //查询用户角色关联表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id",userId);
        List<SysUserRole>  userRoleList = sysUserRoleService.list(queryWrapper);
        Map<Integer, Integer> maps = userRoleList.stream().collect(Collectors.toMap(SysUserRole::getUserId,SysUserRole::getRoleId));

        for(SysUser user:pages.getRecords()){
            UserRoleDto userRoleDto = new UserRoleDto();
            userRoleDto.setRoleId(maps.get(user.getUserId()));
            BeanUtil.copyProperties(user,userRoleDto);
            userRoleDtoList.add(userRoleDto);
        }
        Map map = new HashMap();
        map.put("records",userRoleDtoList);
        map.put("total",pages.getTotal());
        map.put("size",pages.getSize());
        map.put("current",pages.getCurrent());
        map.put("searchCount",true);
        map.put("pages",pages.getPages());

        return  new R<>(map);
    }


    /**
     * id查询用户表
     * @param userId id
     * @return R
     */
    @ApiOperation("通过id查询用户表")
    @GetMapping("/getById")
    @DataSource("sys_db")
    public R<SysUser> getById(@RequestParam("userId") Integer userId){
        return new R<>(sysUserService.getById(userId));
    }

    /**
     * 新增用户表
     * @param user 用户表
     * @return R
     */
    @ApiOperation("新增用户表")
    @PostMapping
    @DataSource("sys_db")
    public R save(@RequestBody UserRoleDto user){
        SysUser  sysUser = new SysUser();
        BeanUtil.copyProperties(user,sysUser);
        sysUser.setPassword(ENCODER.encode(user.getPassword()));
        Boolean flag =  sysUserService.save(sysUser);
        //插入用户角色关联表
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(user.getRoleId());
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRoleService.save(sysUserRole);
        return new R<>(flag);
    }

    /**
     * 修改用户表
     * @param
     * @return R
     */
    @ApiOperation("修改用户表")
    @PutMapping
    @DataSource("sys_db")
    public R updateById(@RequestBody UserRoleDto user){
        Boolean flag =  sysUserService.updateById(user);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",user.getUserId());
        SysUserRole sysUserRole = sysUserRoleService.getOne(queryWrapper);
        if(Objects.nonNull(sysUserRole)){
            sysUserRole.setRoleId(user.getRoleId());
            sysUserRoleService.updateById(sysUserRole);
        }else {
            SysUserRole sysUserRole1 = new SysUserRole();
            sysUserRole1.setUserId(user.getUserId());
            sysUserRole1.setRoleId(user.getRoleId());
            sysUserRoleService.save(sysUserRole1);
        }
        return new R<>(flag);
    }

    /**
     * 通过id删除用户表
     * @param userId id
     * @return R
     */
    @ApiOperation("删除用户表")
    @DeleteMapping("/removeById")
    @DataSource("sys_db")
    public R removeById(@RequestParam("userId") Integer userId){
        return new R<>(sysUserService.removeById(userId));
    }

    /**
     * 查询全部
     * @param
     * @return R
     */
    @ApiOperation("查询全部")
    @GetMapping("/queryAll")
    @DataSource("sys_db")
    public R queryAll(){
        return new R<>(sysUserService.queryUser());
    }

}
